<?php
// +----------------------------------------------------------------------
// | [Sobey Mpmanage] Copyright (c) 2017 http://www.rhaphp.com/
// +----------------------------------------------------------------------
// | [RhaPHP] 并不是自由软件,你可免费使用,未经许可不能去掉RhaPHP相关版权
// +----------------------------------------------------------------------
// | Author: Geeson <qimengkeji@vip.qq.com>
// +----------------------------------------------------------------------


namespace app\admin\controller;

use think\exception\ErrorException;
use think\facade\Cache;
use app\common\model\MediaNewsList;
use app\common\model\MediaNewsMaterial;
use think\Db;
use think\facade\Env;
use think\facade\Request;
use think\facade\Session;

class Mpmanage extends Base
{

    public function initialize()
    {

        parent::initialize();

    }

    /**
     * @author Geeson RHAPHP.COM
     * @param int $type
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function newsList($type = 3)
    {
//       $lists=Db::name('media_news')
//           ->alias('a')
//           ->where(['a.mid'=>0,'a.type'=>$type])
//           ->join('__MEDIA_NEWS_LIST__ b','a.news_id=b.news_id','RIGHT')
//           ->select();
        $url = getHostDomain() . $_SERVER['REQUEST_URI'];
        \session('news_list_url', $url);
        $lists = Db::name('media_news')->where([['mid', '=', 0], ['type', '=', $type]])
            ->order('news_id DESC')
            ->paginate(6);
        $page = $lists->render();
        $news_ids = '';
        foreach ($lists as $val) {
            $news_ids .= $val['news_id'] . ',';
        }
        $model = new MediaNewsList();
        $newsInfos = $model->where('news_id', 'in', $news_ids)
            ->where('title', 'neq', '')
            ->select();
        $newsInfos = json_decode(json_encode($newsInfos), true);
        $infoLists = [];
        foreach ($lists as $key => $val) {
            $infoLists[$key] = $val;
            if (!empty($newsInfos)) {
                foreach ($newsInfos as $key2 => $val2) {
                    //$infoLists[$key]['list']=[];
                    if ($val['news_id'] == $val2['news_id']) {
                        $infoLists[$key]['list'][$key2] = $val2;
                    }
                }
            } else {
                $infoLists[$key]['list'] = [];
            }
        }

        $MpList = $this->getRoleMpList();

        $this->assign('mpList', $MpList);
        $this->assign('intype', $type);
        $this->assign('data', $infoLists);
        $this->assign('page', $page);
        return view('newslist');
    }

    /**
     * @author Geeson RhaPhp.COM
     * @return \think\response\View
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public function addNews()
    {
        if (Request::isAjax()) {
            $In = Request::post();
            if (empty($In['title'])) {
                ajaxMsg(3, '标题不能为空');
            }
            if (isset($In['content']) && $In['content'] == '`$`') {
                ajaxMsg(3, '请检查必填项');
            }
            $model = new MediaNewsList();
            $info['mid'] = 0;
            $info['title'] = $In['title'];
            $info['type'] = $In['type'];
            $info['create_time'] = time();
            $info['update_time'] = time();
            if (!$news_id = Db::name('media_news')->insertGetId($info)) {
                ajaxMsg(0, '增加失败了');
            }
            switch ($In['type']) {
                case 1:
                    if (!$model->save(['news_id' => $news_id, 'content' => $In['title']])) {
                        Db::name('media_news')->where(['mid' => 0, 'news_id' => $news_id])->delete();
                        ajaxMsg(0, '操作失败了');
                    }
                    break;
                case 2:
                    $array = explode('`|`', $In['content']);
                    $news_lists['title'] = $array[0];
                    $news_lists['author'] = $array[1];
                    $news_lists['cover'] = $array[2];
                    $news_lists['show_cover_pic'] = $array[3];
                    $news_lists['digest'] = $array[4];
                    $news_lists['content'] = $array[5];
                    $news_lists['content_source_url'] = $array[6];
                    $news_lists['news_id'] = $news_id;
                    if (!$model->save($news_lists)) {
                        Db::name('media_news')->where(['mid' => 0, 'news_id' => $news_id])->delete();
                        ajaxMsg(0, '操作失败了');
                    }
                    break;
                case 3:
                    $list = explode('`$`', $In['content']);
                    $news_lists = [];
                    foreach ($list as $k => $v) {
                        $array = explode('`|`', $v);
                        $news_lists['title'] = $array[0];
                        $news_lists['author'] = $array[1];
                        $news_lists['cover'] = $array[2];
                        $news_lists['show_cover_pic'] = $array[3];
                        $news_lists['digest'] = $array[4];
                        $news_lists['content'] = $array[5];
                        $news_lists['content_source_url'] = $array[6];
                        $news_lists['news_id'] = $news_id;
                        $model = new MediaNewsList();
                        if (!$model->save($news_lists)) {
                            Db::name('media_news')->where(['mid' => 0, 'news_id' => $news_id])->delete();
                            ajaxMsg(0, '增加图文第' . ($k + 1) . '失败了');
                        }
                    }
                    break;
                case 4:
                    $array = explode('`|`', $In['content']);
                    $news_lists['title'] = $array[0];
                    $news_lists['cover'] = $array[1];
                    $news_lists['digest'] = $array[2];
                    $news_lists['content_source_url'] = $array[3];
                    $news_lists['news_id'] = $news_id;
                    if (!$model->save($news_lists)) {
                        Db::name('media_news')->where(['mid' => 0, 'news_id' => $news_id])->delete();
                        ajaxMsg(0, '操作失败了');
                    }
                    break;
            }
            ajaxMsg(1, '操作成功');
        } else {
            $this->assign('uploadImg', getHostDomain() . \url('uploadMediaNewsImage'));
            return view('addnews');
        }
    }


    /**
     * @author Geeson RHAPHP.com
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function newsPreview()
    {
        if (Request::isAjax()) {
            $mpList = $this->getRoleMpList();
            if(!$mpList){
                ajaxMsg(0, '没有公众号权限');
            }

            foreach ($mpList as $item) {
                if($item['type'] == 2){
                    $mid = $item['id'];
                }

            }
            if(!$mid){
                ajaxMsg(0, '此功能认证公众号才能使用');
            }
            $mp = getMpInfo($mid);
            if ($mp['type'] == 1 || $mp['type'] == 3) {
                ajaxMsg(0, '此功能认证公众号才能使用');
            }
            $news_id = Request::post('news_id');
            $wxid = Request::post('wxid');
            $news = Db::name('media_news')->where(['mid' => 0, 'news_id' => $news_id])->find();
            if (empty($news)) {
                ajaxMsg(0, '内容不存在');
            }

            $custom_message_summary = Db::name('global_config')->where(['code' => 'add_message_summary','admin_id'=>$this->admin_id])->value('value');
            $custom_message_content = Db::name('global_config')->where(['code' => 'add_message_content','admin_id'=>$this->admin_id])->value('value');
            if ($news['type'] != 1 || $news['type'] != 4) {
                if (empty($news['media_id'])) {
                    $model = new MediaNewsList();
                    $lists = $model->where('news_id', 'in', $news_id)->select();
                    if (empty($lists))
                        ajaxMsg('0', '没有内容可上传');
                    $array = [];
                    foreach ($lists as $key => $val) {
                        $F = explode(getHostDomain(), $val['cover']);
                        if (isset($F['1'])) {
                            $filePath = substr($F['1'], 1);
                            //为了不占用5000张素材空间，这里上传为临时素材，有效果为3天
                            if ($result = uploadMedia($filePath, 'image')) {
                                $lists[$key]['thumb_media_id'] = $result['media_id'];
                                $model->save(['thumb_media_id' => $result['media_id']], ['id' => $val['id']]);
                            }

                        }
                        $array[$key]['thumb_media_id'] = $lists[$key]['thumb_media_id'];
                        $array[$key]['author'] = $val['author'];
                        $array[$key]['title'] = $val['title'];
                        $array[$key]['content_source_url'] = $val['content_source_url'];
                        $array[$key]['content'] = $val['content'].$custom_message_content;
                        $array[$key]['digest'] = $val['digest'].$custom_message_summary;
                        $array[$key]['show_cover_pic'] = $val['show_cover_pic'];

                    }
                    $articleList['articles'] = $array;

                    $wxObj = getWechatActiveObj($mid);
                    if ($result = $wxObj->uploadArticles($articleList)) {
                        if (Db::name('media_news')->where('news_id', $news_id)->update(['media_id' => $result['media_id'], 'status_type' => 1])) {
                            $news['media_id'] = $result['media_id'];
                            $news['status_type'] = 1;
                        } else {
                            ajaxMsg(0, '保存数据失败');
                        }
                    } else {
                        if (isset($wxObj->errCode) && !empty($wxObj->errCode)) {
                            ajaxMsg(0, '公众号【'.$mp['name'].'】上传失败：错误码：' . $wxObj->errCode . ' 错误内容为：' . $wxObj->errMsg);
                        } else {
                            ajaxMsg('0', '公众号【'.$mp['name'].'】未知错误');
                        }
                    }
                }
            }



            if ($news['type'] == 1) {
                $data = [
                    'towxname' => $wxid,
                    'text' => [
                        'content' => $news['title'],
                    ],
                    'msgtype' => 'text',

                ];
            }else if ($news['type'] == 4) {
                $media_news = Db::name('media_news_list')->where(['news_id' => $news['news_id']])->find();

                $data = [
                    'news' => [
                        'articles' => array(
                            'title'=>$news['title'],
                            'description'=>$media_news['digest'].$custom_message_summary,
                            'url'=>$media_news['content_source_url'],
                            'picurl'=>$media_news['cover'],
                           // 'picurl'=>'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533038665420&di=dfc1bc453fa24d15dd2140287d8e02a7&imgtype=0&src=http%3A%2F%2Fg.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F79f0f736afc37931ccb794e8e7c4b74542a91117.jpg',
                        ),
                    ],
                    'msgtype' => 'news',
                ];
            }  else {
                $data = [
                    'towxname' => $wxid,
                    'msgtype' => 'mpnews',
                    'mpnews' => [
                        'media_id' => $news['media_id']
                    ],
                ];
            }

            $wxObj = getWechatActiveObj($mid);
            $result = $wxObj->previewMassMessage($data);

            if ($result && isset($result['errcode']) && $result['errcode'] == 0) {
                ajaxMsg(1, '发送成功，请打开发送者微信进行预览');
            } else {
                ajaxMsg(0, '发送失败，错误码：' . $wxObj->errCode . ' 错误内容：' . $wxObj->errMsg);
            }

        }
    }

    /**
     * @author Geeson rhaphp.com
     * @param string $news_id
     * @param string $type
     * @return \think\response\View
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function editNews($news_id = '', $type = '')
    {

        if (empty($news_id) || empty($type)) {
            $this->error('没有相应的内容');
        }
        $result = Db::name('media_news')->where(['news_id' => $news_id])->find();
        if ($result['mid'] != 0) {
            $this->error('修改内容不存在或者与公众号不匹配');
        }
        if (Request::isAjax()) {
            $In = Request::post();
            if (empty($In['title'])) {
                ajaxMsg(3, '标题不能为空');
            }
            if (isset($In['content']) && $In['content'] == '`$`') {
                ajaxMsg(3, '请检查必填项');
            }
            $model = new MediaNewsList();
            switch ($type) {
                case 1:
                    $res = Db::name('media_news')
                        ->where(['mid' => 0, 'news_id' => $news_id])
                        ->update(['title' => $In['title'], 'update_time' => time()]);
                    if ($res) {
                        $model->save(['content' => $In['title']], ['news_id' => $news_id]);
                        ajaxMsg(1, '修改成功');
                    } else {
                        ajaxMsg(0, '操作成功，但内容没有发生改变');
                    }
                    break;
                case 2:
                    $array = explode('`|`', $In['content']);
                    $data['title'] = $array[0];
                    $data['author'] = $array[1];
                    $data['cover'] = $array[2];
                    $data['show_cover_pic'] = $array[3];
                    $data['digest'] = $array[4];
                    $data['content'] = $array[5];
                    $data['content_source_url'] = $array[6];
                    if ($model->save($data, ['news_id' => $news_id])) {
                        Db::name('media_news')
                            ->where(['mid' => 0, 'news_id' => $news_id])
                            ->update(['title' => $In['title'], 'update_time' => time(), 'status_type' => 0]);
                    }
                    ajaxMsg(1, '修改成功');
                    break;
                case 3:
                    $res = Db::name('media_news')
                        ->where(['mid' => 0, 'news_id' => $news_id])
                        ->update(['title' => $In['title'], 'update_time' => time(), 'status_type' => 0]);
                    if (!$res) {
                        ajaxMsg(0, '更新状态失败');
                    }
                    $list = explode('`$`', $In['content']);
                    $data = [];
                    foreach ($list as $k => $v) {
                        $array = explode('`|`', $v);
                        $data[$k]['title'] = $array[0];
                        $data[$k]['author'] = $array[1];
                        $data[$k]['cover'] = $array[2];
                        $data[$k]['show_cover_pic'] = $array[3];
                        $data[$k]['digest'] = $array[4];
                        $data[$k]['content'] = $array[5];
                        $data[$k]['content_source_url'] = $array[6];
                        $data[$k]['news_id'] = $news_id;
                    }
                    $model = new  MediaNewsList();
                    $model->where('news_id', $news_id)->delete();
                    if ($model->insertAll($data)) {
                        ajaxMsg(1, '修改成功');
                    } else {
                        ajaxMsg(0, '保存失败，建议不要关闭页面，检查好填写项再次提交');
                    }
                    break;
                case 4:
                    $array = explode('`|`', $In['content']);
                    $data['title'] = $array[0];
                    $data['cover'] = $array[1];
                    $data['digest'] = $array[2];
                    $data['content_source_url'] = $array[3];
                    if ($model->save($data, ['news_id' => $news_id])) {
                        Db::name('media_news')
                            ->where(['mid' => 0, 'news_id' => $news_id])
                            ->update(['title' => $In['title'], 'update_time' => time(), 'status_type' => 0]);
                    }
                    ajaxMsg(1, '修改成功');
                    break;


            }
        } else {
            $newsInfo = Db::name('media_news')->where(['mid' => 0, 'type' => $type, 'news_id' => $news_id])->find();

            $model = new MediaNewsList();
            $newsInfos = $model->where('news_id', '=', $news_id)
                ->select();
            $newsInfos = json_decode(json_encode($newsInfos), true);
            $newsInfo['list'] = $newsInfos;

            switch ($type) {
                case 1:
                    if (isset($newsInfo['list']['0']['content'])) {
                        $content = $newsInfo['list']['0']['content'];
                    } else {
                        //此有两个个可能，在增加图文时插入内容时失败，另一个内容为空，是没有办法做修改功能的，所以建议删除重新增加
                        $content = '没有此图文内容，建议你将此图文删除，重新增加';
                    }
                    $this->assign('content', $content);
                    break;
                case 2:
                    if (isset($newsInfo['list']['0'])) {
                        $newsInfo = $newsInfo['list']['0'];
                    } else {
                        $newsInfo = [];
                    }
                    $this->assign('info', $newsInfo);
                    break;
                case 3:
                    if (isset($newsInfo['list']) && !empty($newsInfo['list'])) {
                        $newsInfo = $newsInfo['list'];
                    } else {
                        $newsInfo = [];
                    }
                    $this->assign('info', $newsInfo);
                    break;
                case 4:
                    if (isset($newsInfo['list']['0'])) {
                        $newsInfo = $newsInfo['list']['0'];
                    } else {
                        $newsInfo = [];
                    }
                    $this->assign('info', $newsInfo);
                    break;
            }
            $this->assign('news_id', $news_id);
            $this->assign('back_url', \session('news_list_url'));
            $this->assign('uploadImg', getHostDomain() . \url('uploadMediaNewsImage'));
            $this->assign('type', $type);
            return view('editnews');
        }
    }

    /**
     * @author geeson rhaphp.com
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function delMediaNews()
    {
        if (Request::isAjax()) {
            if ($news_id = Request::post('id')) {
                $result = Db::name('media_news')->where(['news_id' => $news_id])->find();
                if ($result['mid'] != 0) {
                    ajaxMsg(0, '删除失败，内容与公众号不吻合');
                }
                Db::name('media_news')->where(['mid' => 0, 'news_id' => $news_id])->delete();
                Db::name('media_news_list')->where(['news_id' => $news_id])->delete();
                ajaxMsg(1, '删除成功');
            }
        }
    }


    public function sendall()
    {

        if (Request::isAjax()) {

            $news_id = Request::post('news_id');
            $news = Db::name('media_news')->where(['mid' => 0, 'news_id' => $news_id])->find();
            if (empty($news)) {
                ajaxMsg(0, '内容不存在');
            }
            $media_news_list = Db::name('media_news_list')->where(['news_id' => $news_id])->select();

            $mpids = Request::post('mp_ids');
            $mpid_arr = array();
            if(strlen($mpids)>0){
                $mpid_arr = explode(',',$mpids);
            }
            if(!$mpid_arr){
                ajaxMsg(0, '请选择公众号');
            }
            $MpList = $this->getRoleMpList();

            $mp_id_list = array();
            foreach ($MpList as $item) {

                $mp_id_list[$item['id']] = $item;
            }

            foreach ($mpid_arr as $item) {
                if(!isset($mp_id_list[$item]) || !$mp_id_list[$item]){
                    ajaxMsg(0, '没有所选公众号权限');
                }
                $mp = $mp_id_list[$item];
                if ($mp['type'] == 1 || $mp['type'] == 3) {
                    ajaxMsg(0, '此功能认证公众号才能使用,【'.$mp['name'].'】不是认证公众号');
                }

            }
            $news_list = array();
            foreach ($mpid_arr as $item) {
                $news_data =  $news;
                $news_data['mid'] = $item;
                $news_data['create_time'] = time();
                $news_data['update_time'] = time();
                unset($news_data['news_id']);
                $this_news_id = Db::name('media_news')->insertGetId($news_data);
                $news_data['news_id'] = $this_news_id;
                $news_list[] = $news_data;
                if($this_news_id <= 0){
                    ajaxMsg(0, '发送失败');
                }
                foreach ($media_news_list as $mnitem) {
                    $news_media_data =  $mnitem;
                    $news_media_data['news_id'] = $this_news_id;
                    unset($news_media_data['id']);
                    $this_news_media_id = Db::name('media_news_list')->insertGetId($news_media_data);
                    if($this_news_media_id <= 0){
                        ajaxMsg(0, '发送失败');
                    }
                }
            }
            $custom_message_summary = Db::name('global_config')->where(['code' => 'add_message_summary','admin_id'=>$this->admin_id])->value('value');
            $custom_message_content = Db::name('global_config')->where(['code' => 'add_message_content','admin_id'=>$this->admin_id])->value('value');
            if ($news['type'] != 1 && $news['type'] != 4) {

                foreach ($news_list as $k=>$item) {

                    $mp = $mp_id_list[$item['mid']];
                    $news_id = $item['news_id'];
                    $model = new MediaNewsList();
                    $lists = $model->where('news_id', 'in', $news_id)->select();
                    if (empty($lists)) continue;
                    $array = [];
                    foreach ($lists as $key => $val) {
                        $F = explode(getHostDomain(), $val['cover']);
                        if (isset($F['1'])) {
                            $filePath = substr($F['1'], 1);
                            //为了不占用5000张素材空间，这里上传为临时素材，有效果为3天
                            if ($result = uploadMedia($filePath, 'image')) {
                                $lists[$key]['thumb_media_id'] = $result['media_id'];
                                $model->save(['thumb_media_id' => $result['media_id']], ['id' => $val['id']]);
                            }

                        }
                        $array[$key]['thumb_media_id'] = $lists[$key]['thumb_media_id'];
                        $array[$key]['author'] = $val['author'];
                        $array[$key]['title'] = $val['title'];
                        $array[$key]['content_source_url'] = $val['content_source_url'];
                        $array[$key]['content'] = $val['content'].$custom_message_content;
                        $array[$key]['digest'] = $val['digest'].$custom_message_summary;
                        $array[$key]['show_cover_pic'] = $val['show_cover_pic'];

                    }
                    $articleList['articles'] = $array;

                    $wxObj = getWechatActiveObj($item['mid']);
                    if ($result = $wxObj->uploadArticles($articleList)) {
                        if (Db::name('media_news')->where('news_id', $news_id)->update(['media_id' => $result['media_id'], 'status_type' => 1])) {
                            $news_list[$k]['media_id'] = $result['media_id'];
                            $news_list[$k]['status_type'] = 1;

                        } else {
                            ajaxMsg(0, '保存数据失败');
                        }
                    } else {
                        if (isset($wxObj->errCode) && !empty($wxObj->errCode)) {
                            ajaxMsg(0, '公众号【'.$mp['name'].'】上传失败：错误码：' . $wxObj->errCode . ' 错误内容为：' . $wxObj->errMsg);
                        } else {
                            ajaxMsg('0', '公众号【'.$mp['name'].'】未知错误');
                        }
                    }


                }

            }
            $fails = array();
            $success = array();

            foreach ($news_list as $item) {
                $mp = $mp_id_list[$item['mid']];
//                if ($item['type'] == 1) {
//                    $data = [
//                        'filter' => [
//                            'is_to_all' => true,
//                            'tag_id' => ''
//                        ],
//                        'text' => [
//                            'content' => $item['title'],
//                        ],
//                        'msgtype' => 'text',
//
//                    ];
//                } else {
//                    $data = [
//                        'filter' => [
//                            'is_to_all' => true
//                        ],
//                        'msgtype' => 'mpnews',
//                        'mpnews' => [
//                            'media_id' => $item['media_id']
//                        ],
//                        'send_ignore_reprint' => 0
//                    ];
//                }
                if ($item['type'] == 1) {
                    $data = [
                        'text' => [
                            'content' => $item['title'],
                        ],
                        'msgtype' => 'text',
                    ];
                }else if ($item['type'] == 4) {
                    $media_news = Db::name('media_news_list')->where(['news_id' => $item['news_id']])->find();

                    $data = [
                        'news' => [
                            'articles' => array(
                                array(
                                    'title'=>$item['title'],
                                    'description'=>$media_news['digest'].$custom_message_summary,
                                    'url'=>$media_news['content_source_url'],
                                    'picurl'=>$media_news['cover'],
                                    //'picurl'=>'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533038665420&di=dfc1bc453fa24d15dd2140287d8e02a7&imgtype=0&src=http%3A%2F%2Fg.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F79f0f736afc37931ccb794e8e7c4b74542a91117.jpg'
                                )
                            )
                        ],
                        'msgtype' => 'news',
                    ];
                } else {

                    $data = [
                        'msgtype' => 'mpnews',
                        'mpnews' => [
                            'media_id' => $item['media_id']
                        ]
                    ];
                }


                $wxObj = getWechatActiveObj($item['mid']);
//                $FriendList = Db::name('mp_friends')->where(['mpid' => $item['mid'], 'subscribe' => 1,['subscribe_time', '>', time()-172800]])
//                 ->select();
                $FriendList = Db::name('mp_friends')->where(['mpid' => $item['mid'], 'subscribe' => 1])
                    ->select();
                foreach ($FriendList as $friend) {
                    $data['touser'] = $friend['openid'];
                    $result = $wxObj->sendCustomMessage($data);
                    if ($result && isset($result['errcode']) && $result['errcode'] == 0) {
                        $success[] = $mp['name'];
                    } else {
                        $fails[] = '公众号【'.$mp['name'].'】群发失败，错误码：' . $wxObj->errCode . ' 错误内容：' . $wxObj->errMsg;
                    }
                }


//                $result = $wxObj->sendGroupMassMessage($data);
//                if ($result && isset($result['errcode']) && $result['errcode'] == 0) {
//                    $success[] = $mp['name'];
//                } else {
//                    $fails[] = '公众号【'.$mp['name'].'】群发失败，错误码：' . $wxObj->errCode . ' 错误内容：' . $wxObj->errMsg;
//                }
//
            }

            if(!$fails){
                ajaxMsg(0, '群发成功');
            }else{
                if($success){
                    ajaxMsg(1, '群发成功公众号,'.implode(';',$success).';群发失败公众号,'.implode(';',$fails));
                }else{
                    ajaxMsg(1, '群发失败,'.implode(';',$fails));
                }

            }


        }
    }

    public function uploadMediaNewsImage()
    {
        if (Request::isPost()) {
            $file = \request()->file('upfile');
            $info = $file->rule('md5')->validate(['ext' => 'jpg,png'])->move(ROOT_PATH . DS . ENTR_PATH . DS . 'uploads');
            if ($info) {
                $imgFile = '@' . ROOT_PATH . DS . ENTR_PATH . DS . 'uploads' . DS . $info->getSaveName();
                $wxObj = getWechatActiveObj(0);
                $result = $wxObj->uploadImg(['media' => $imgFile]);
                if ($result && isset($result['url']) && !empty($result['url'])) {
                    $data = [
                        'mid' => 0,
                        'url' => $result['url'],
                        'create_time' => time(),
                        'type' => 1,
                        'path' => DS . 'uploads' . DS . $info->getSaveName(),
                    ];
                    Db::name('media_news_material')->insert($data);
                    $ueInfo = [
                        "state" => "SUCCESS",          //上传状态，上传成功时必须返回"SUCCESS"
                        "url" => $result['url'],            //返回的地址
                        "title" => "",          //新文件名
                        "original" => "",       //原始文件名
                        "type" => "",            //文件类型
                        "size" => "",           //文件大小
                    ];
                    return json_encode($ueInfo);
                } else {
                    $ueInfo = [
                        "state" => '群发失败，错误码：' . $wxObj->errCode . ' 错误内容：' . $wxObj->errMsg,          //上传状态，上传成功时必须返回"SUCCESS"
                        "url" => '',            //返回的地址
                        "title" => "",          //新文件名
                        "original" => "",       //原始文件名
                        "type" => "",            //文件类型
                        "size" => "",           //文件大小
                    ];
                    return json_encode($ueInfo);
                }

            } else {
                $ueInfo = [
                    "state" => '上传失败，图片类型只支持jpg,png',          //上传状态，上传成功时必须返回"SUCCESS"
                    "url" => '',            //返回的地址
                    "title" => "",          //新文件名
                    "original" => "",       //原始文件名
                    "type" => "",            //文件类型
                    "size" => "",           //文件大小
                ];
                return json_encode($ueInfo);
            }
        }
    }

    public function getNewsMediaMeterial()
    {
        $in = input();
        $model = new MediaNewsMaterial();
        $mediaLists = $model->where('mid', 0)
            ->where('type', 1)
            ->order('id DESC')
            ->limit($in['start'], $in['size'])->select();
        if (!empty($mediaLists)) ;
        {
            $count = count($mediaLists);
            $list = [];
            foreach ($mediaLists as $key => $val) {
                $list [$key]['url'] = $val['url'];
                $list [$key]['path'] = $val['path'];
            }

            $result = json_encode(array(
                "state" => "SUCCESS",
                "list" => $list,
                "start" => $in['start'],
                "total" => '1000'
            ));

            return $result;
        }
    }


}